#!/bin/bash
# 安装MongoDB及配置服务

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_mongodb() {
    local version=`echo ${Version} |awk -F. '{print $1}' `
    local appname="mongodb-linux-x86_64-rhel70-${Version}.tgz"
    local link="${MONGODB_NAME}${Version}.tgz"
    
    if [ ! -e "${APPS_HOME}/${appname}" ];then
        echo "正在下载MongoDB ${Version}..."
        wget -P ${APPS_HOME} $link
        if [ $? -ne 0 ]; then
            error_exit "MongoDB下载失败"
        fi
    fi
    
    # 备份现有版本
    if [ -e ${Basedir}/mongodb ];then
        local old_version=$(${Basedir}/mongodb/bin/mongo -version|grep Mon|awk '{print $NF}'|tr -d "v")
        local oldv="${Basedir}/mongodb_${old_version}_$(date +%Y%m%d)"
        mv ${Basedir}/mongodb ${oldv}
        echo "已将现有MongoDB备份至 ${oldv}"
    fi
    
    mkdir -p ${Basedir}/mongodb 
    tar -xf ${APPS_HOME}/${appname} -C ${Basedir}/mongodb --strip-components 1 
    mkdir -p ${Basedir}/mongodb/{data,logs,etc} 
    touch ${Basedir}/mongodb/logs/mongodb.log
    
    # 创建配置文件
    if [[ ! -f "${Basedir}/mongodb/etc/mongodb.conf" ]];then
        echo "创建mongodb配置文件"
        cat > ${Basedir}/mongodb/etc/mongodb.conf <<EOF
#数据库路径
dbpath=${Basedir}/mongodb/data
#日志路径
logpath=${Basedir}/mongodb/logs/mongodb.log
#错误日志采用追加模式
logappend=true
#启用日志
journal=true
#过滤无用日志
quiet=true
#端口号
port=27017
#允许远程
bind_ip=0.0.0.0
#开启子进程
fork=true
EOF
    else
        echo "mongodb配置文件已存在"
    fi
    
    # 创建软链接
    rm -f /usr/local/bin/mongo
    rm -f /usr/local/bin/mongod
    ln -s ${Basedir}/mongodb/bin/mongod /usr/local/bin/
    ln -s ${Basedir}/mongodb/bin/mongo /usr/local/bin/
    
    # 设置权限
    chown -R root:root ${Basedir}/mongodb
}

function configure_mongodb_service() {
    if [[ ! -f "${MONGODB_SERVICE}" ]];then
        echo "创建mongodb服务文件"
        cat > ${MONGODB_SERVICE} <<EOF
[Unit]
Description=mongodb
After=syslog.target
After=network.target
After=mongodb.service

[Service]
Type=forking
ExecStart=/usr/local/bin/mongod --config ${Basedir}/mongodb/etc/mongodb.conf
ExecStop=/usr/local/bin/mongod -shutdown --config ${Basedir}/mongodb/etc/mongodb.conf

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl start mongodb
        systemctl enable mongodb
        
        mongo --version
        if [ $? -eq 0 ];then
            success_msg "mongodb ${Version} 安装成功"
        else
            error_exit "mongodb ${Version} 安装失败"
        fi
    else
        echo "mongodb服务文件已存在"
    fi
}

echo "开始安装MongoDB..."

read -p "输入需要的mongodb版本(默认3.6.23): " Version
if [ -z "${Version}" ];then
    Version="3.6.23"
    echo "使用默认版本: $Version"
fi

install_mongodb
configure_mongodb_service
